package com.shu.rateLimiter;

import com.google.common.util.concurrent.RateLimiter;
import com.shu.timerTask.Base;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

/**
 * @author ssm
 * @version V1.0
 * @description: guava令牌桶实现该算法 - 限流
 * @date 2019/4/8 21:29
 */

public class GuavaRateLimiter extends Base {

    RateLimiter rateLimiter = RateLimiter.create(2); // 每秒生产2个令牌供使用

    @Test
    public void name() {
        stopWatch.start();
        String fmt = "阻塞了%s秒,现在过去了:%s ms";
        System.out.println(String.format(fmt, rateLimiter.acquire(1), stopWatch.elapsed(TimeUnit.MILLISECONDS)));
        System.out.println(String.format(fmt, rateLimiter.acquire(5), stopWatch.elapsed(TimeUnit.MILLISECONDS)));
        System.out.println(String.format(fmt, rateLimiter.acquire(10), stopWatch.elapsed(TimeUnit.MILLISECONDS)));
        System.out.println(String.format(fmt, rateLimiter.tryAcquire(10), stopWatch.elapsed(TimeUnit.MILLISECONDS)));
        System.out.println(String.format(fmt, rateLimiter.tryAcquire(10, 10, TimeUnit.SECONDS), stopWatch.elapsed(TimeUnit.MILLISECONDS)));
    }

}